/**
 * @Title: HomeActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月19日 上午8:19:23
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import android.annotation.SuppressLint;
import android.content.*;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android_serialport_api.SerialPortManager;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.adapter.HomeModelAdapter;
import com.jason.fingerprint.beans.OrganBean;
import com.jason.fingerprint.beans.SponsorInfo;
import com.jason.fingerprint.beans.UserBean;
import com.jason.fingerprint.beans.WorkVisitBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.beans.ui.ModelBean;
import com.jason.fingerprint.beans.ui.SoundBean;
import com.jason.fingerprint.common.DialogHelper;
import com.jason.fingerprint.common.PreferenceHelper;
import com.jason.fingerprint.common.RemainingTimeCalculator;
import com.jason.fingerprint.common.SoundRecorder;
import com.jason.fingerprint.configs.DataConfig;
import com.jason.fingerprint.logic.DatbOrganSyncLogic;
import com.jason.fingerprint.logic.DatbRecordSyncLogic;
import com.jason.fingerprint.logic.DatbSelectOrganByIdSyncLogic;
import com.jason.fingerprint.logic.UploadToTempSyncLogic;
import com.jason.fingerprint.service.SoundRecorderService;
import com.jason.fingerprint.utils.DataUtils;
import com.jason.fingerprint.widget.LoadingDialog;
import de.greenrobot.event.EventBus;
import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;
import org.kymjs.aframe.utils.SystemTool;

import java.io.File;

/**
 * @ClassName: HomeActivity
 * @Description: 主页
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月19日 上午8:19:23
 */
@SuppressLint("HandlerLeak")
public class HomeActivity extends BaseActivity implements View.OnClickListener,SoundRecorder.OnStateChangedListener, SoundRecorderService.StopRecordCallback {

	private static final String TAG = HomeActivity.class.getSimpleName();

	@BindView(id = R.id.home_gridview)
	private GridView mGridView;
	private TextView mUsernfoTextView;

	private HomeModelAdapter mHomeModelAdapter;
	private KJDB mKjdb;
	private LoadingDialog mProgressDialog;
	private boolean isAyncData = false;// 是否正在同步数据

	@BindView(id = R.id.header_title)
	private TextView mTitleTextView;

	private long mExitTime = 0;
	private boolean mIsToHome = false;

	public static HomeActivity mHomeActivity = null;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_home);
	}

	// 初始化视图
	@Override
	protected void initWidget() {
		super.initWidget();
//		if (android.os.Build.VERSION.SDK_INT > 9) {
//		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//		    StrictMode.setThreadPolicy(policy);
//		}
		mHomeActivity = this;
		mTitleTextView.setText("社区矫正");
		mKjdb = AppContext.getInstance().getKjdb();
		// mGridView = (GridView) findViewById(R.id.home_gridview);
		mHomeModelAdapter = new HomeModelAdapter(this);
		mGridView.setAdapter(mHomeModelAdapter);
		mGridView.setOnItemClickListener(new HomeModelItemClickListener());
		mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		Intent intent = getIntent();
		if (intent != null){
			mIsToHome = intent.getBooleanExtra("is_to_loading_activity",false);
		}

		mUsernfoTextView = (TextView) findViewById(R.id.home_info);
		mProgressDialog = new LoadingDialog(this);
		mProgressDialog.setIsOut(false);
		mProgressDialog.setMessage("数据正在加载中，请稍等...");

		initRecorder();
	}

	// 初始化数据
	@Override
	protected void initData() {
		super.initData();
		// 加载登录帐号下可选择的隶属机构
		if (SystemTool.checkNet(AppContext.getAppContext()) && !AppContext.BUGLY_DEBUG) {
			// 初始化人员部门信息
			if (mIsToHome){
				if (AppContext.getInstance().isSynchronizedRecord()){
					mKjdb.deleteByWhere(OrganBean.class, null);
					DatbOrganSyncLogic datbOrganSyncLogic = new DatbOrganSyncLogic(
							AppContext.getInstance(), mRecordSyncHandler, false);
					datbOrganSyncLogic.execute();
					// 初始化矫正人员信息
					if (!mProgressDialog.isShowing()) {
						mProgressDialog.show();
					}
					initRecordSync(1);
				}
			}

		}
		updateUserInfo();
	}

	// 更新用户信息
	private void updateUserInfo() {
		mUsernfoTextView.setVisibility(View.VISIBLE);
		UserBean bean = AppContext.getInstance().getUserBean();
		StringBuffer buffer = new StringBuffer();
		if (AppContext.getInstance().isLogin()) {
			Log.i(TAG, bean.toString());
			String name = bean.getUserName();
			if (!StringUtils.isEmpty(name)) {
				buffer.append("登录用户：");
				buffer.append(name);
			}
			String organ = "";
			if (!TextUtils.isEmpty(bean.getOrgan())){
				organ = bean.getOrgan();
			}
			buffer.append("    隶属机构：" + organ);
			mUsernfoTextView.setText(buffer.toString());
		} else {
			mUsernfoTextView.setVisibility(View.GONE);
		}
	}

	// 档案同步
	private Handler mRecordSyncHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.cancel();
			}
			isAyncData = false;
			int code = msg.arg1;
			switch (code) {
				case 0:
					Toast.makeText(AppContext.getAppContext(),
							"同步成功,共计" + msg.arg2 + "名，查看具体信息请到档案查询中查询",
							Toast.LENGTH_LONG).show();
					PreferenceHelper.setLoginDate(HomeActivity.this, DataUtils.getToday());
					break;

				default:
					Toast.makeText(AppContext.getAppContext(), "同步失败", Toast.LENGTH_SHORT).show();
					break;
			}
		}
	};

	// 进入指纹录入鉴权
	private Handler mAuthorityRecordHandle = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case 0:
					Intent intent = new Intent(HomeActivity.this,
							RecordActivity.class);
					intent.putExtra(RecordActivity.RECORD_STATE,
							RecordActivity.ADD_RECORD_STATE);
					startActivity(intent);
					break;
				case 1:
					String error = (String) msg.obj;
					Toast.makeText(AppContext.getAppContext(), error, Toast.LENGTH_SHORT).show();
				default:
					Toast.makeText(AppContext.getAppContext(), "权限不足，无法访问", Toast.LENGTH_SHORT)
							.show();
					break;
			}
		};
	};

	private class HomeModelItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
								long id) {
			ModelBean bean = (ModelBean) parent.getItemAtPosition(position);
			switch (bean.getIconId()) {
				case R.drawable.module_icon_luru_selector:
					//  指纹录入
					if (isAyncData) {
						Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
								Toast.LENGTH_SHORT).show();
						return;
					}
					if (SystemTool.checkNet(AppContext.getAppContext())) {
						// 鉴权，只有权限的人才能指纹录入或者修改，此接口现在有问题？？？？？？
						DatbSelectOrganByIdSyncLogic logic = new DatbSelectOrganByIdSyncLogic(
								AppContext.getInstance(), mAuthorityRecordHandle, true);
						logic.execute();
					} else {
						DialogHelper.openNetSettingsDialog(HomeActivity.this);
					}
					break;
				case R.drawable.module_icon_tongbu_selector:
					// 档案同步
					if (isAyncData) {
						Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
								Toast.LENGTH_SHORT).show();
						return;
					}
					initRecordSync(2);
					break;
				case R.drawable.module_icon_chaxun_selector:
					//  档案查询
					if (isAyncData) {
						Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
								Toast.LENGTH_SHORT).show();
						return;
					}
					Intent intent = new Intent(HomeActivity.this,
							RecordActivity.class);
					intent.putExtra(RecordActivity.RECORD_STATE,
							RecordActivity.QUERY_RECORD_STATE);
					startActivity(intent);
					break;
				case R.drawable.module_icon_fuwu_selector:
					//  社区服务
					if (isAyncData) {
						Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
								Toast.LENGTH_SHORT).show();
						return;
					}
					Intent communityServiceIntent = new Intent(HomeActivity.this,
							CommunityServiceActivity.class);
					communityServiceIntent.putExtra("CommunityService", true);
					startActivity(communityServiceIntent);
					break;
				case R.drawable.module_icon_xuexi_selector:
					//  教育学习
					if (isAyncData) {
						Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
								Toast.LENGTH_SHORT).show();
						return;
					}
					Intent studyServiceIntent = new Intent(HomeActivity.this,
							CommunityServiceActivity.class);
					studyServiceIntent.putExtra("CommunityService", false);
					startActivity(studyServiceIntent);
					break;
				case R.drawable.module_icon_baodao_selector:
					//  日常报到
					if (isAyncData) {
						Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
								Toast.LENGTH_SHORT).show();
						return;
					}
					startActivity(new Intent(HomeActivity.this,
							DailyReportActivity.class));
					break;
				case R.drawable.module_icon_zoufang_selector:
					//  工作走访
					if (isAyncData) {
						Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
								Toast.LENGTH_SHORT).show();
						return;
					}
					startActivity(new Intent(HomeActivity.this,
							WorkVisitActivity.class));
					break;
				case R.drawable.module_icon_qingjia_selector:
					//  外出请假
					if (isAyncData) {
						Toast.makeText(AppContext.getAppContext(), "数据正在同步中,请稍等...",
								Toast.LENGTH_SHORT).show();
						return;
					}
					startActivity(new Intent(HomeActivity.this,
							LeaveOutActivity.class));
					break;
				case R.drawable.module_icon_tongzhi_selector:
					//  工作通知
					// workNotice();
					startActivity(new Intent(HomeActivity.this,
							WorkNotifyActivity.class));
					break;
				case R.drawable.module_icon_tixing_selector:
					//  工作提醒
					Toast.makeText(HomeActivity.this,"功能暂未开放",Toast.LENGTH_SHORT).show();
//				startActivity(new Intent(HomeActivity.this,
//						WorkRemindActivity.class));
					break;
				case R.drawable.module_icon_peizhi_selector:
					//  系统配置
					startActivity(new Intent(HomeActivity.this,
							SettingActivity.class));
					break;
				case R.drawable.module_icon_women_selector:
					//  关于我们
					startActivity(new Intent(HomeActivity.this, AboutActivity.class));
					break;

				default:
					break;
			}
		}

	}

	// 档案同步
	private void initRecordSync(int state) {
		if (SystemTool.checkNet(AppContext.getAppContext())) {
			if (!isAyncData) {
				if (state == 2) {//点击加载的收
					mProgressDialog.setIsOut(false);
					mProgressDialog.setTitle("数据同步");
					mProgressDialog.setMessage("正在同步档案中，请稍等...");
					mProgressDialog.show();
				}
				// 同步数据之前，需要把old data delete
				isAyncData = true;
				DatbRecordSyncLogic datbRecordSyncLogic = new DatbRecordSyncLogic(
						AppContext.getInstance(), mRecordSyncHandler, true);
				datbRecordSyncLogic.execute();
			} else {
				Toast.makeText(AppContext.getAppContext(), "数据正在同步中",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			if (state == 2) {
				DialogHelper.openNetSettingsDialog(HomeActivity.this);
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - mExitTime) > 2000) {
				Toast.makeText(AppContext.getAppContext(), "再按一次退出应用",
						Toast.LENGTH_SHORT).show();
				mExitTime = System.currentTimeMillis();
			} else {
				stopRecorder();
				KJActivityManager.create().AppExit(HomeActivity.this);
				SerialPortManager.getInstance().closeSerialPort();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		stopRecorder();
		mTimeHandler.removeCallbacks(mUpdateTimer);
		if (mRecorder != null) {
			mRecorder.removeOnStateChangedListener(this);
		}
		unbindService(mServiceConnection);
		if (mService.getRecordState() == SoundRecorder.STATE_IDLE) {
			stopService(new Intent(this, SoundRecorderService.class));
		}
		unregisterReceiver(mRecordBroadcastReceiver);
		mHomeActivity = null;
	}

	public static final String INTENT_RECORD_START = "intent_record_start";
	public static final String INTENT_RECORD_STOP = "intent_record_stop";
	public static final String KEY_RECORD_SOUND = "key_record_sound";

	private static final long MAX_RECORD_TIME = 1 * 60 * 60L;//录音一个小时

	public static int RECORDER_STATE = SoundRecorder.STATE_IDLE;

	private TextView mFileNameTextView,mTimeTextView,mEmptyTextView;
	private ImageView mStopImageView,mGoonImageView,mPauseImageView;
	private RelativeLayout mMainRelativeLayout;

	public static MainActivity instance = null;
	public SoundRecorderService mService = null;
	private SoundRecorder mRecorder;
	private RemainingTimeCalculator mRemainingTimeCalculator;//计算录音时间
	private int mAudioSourceType = MediaRecorder.AudioSource.MIC;
	private long mMaxFileSize = -1; // can be specified in the intent

	private String mRequestedType = DataConfig.AUDIO_WAVE;

	private String mErrorUiMessage = null;
	private String mTimerFormat;
	private String mLastFileName;
	private AudioManager mAudioManager;
	private SoundBean mSoundBean;


	private void initRecorder(){
		mMainRelativeLayout = (RelativeLayout) findViewById(R.id.recorder_main);
		mFileNameTextView = (TextView) findViewById(R.id.recorder_name);
		mTimeTextView = (TextView) findViewById(R.id.recorder_time);
		mEmptyTextView = (TextView) findViewById(R.id.home_empty);
		mStopImageView = (ImageView) findViewById(R.id.recorder_stop);
		mGoonImageView = (ImageView) findViewById(R.id.recorder_goon);
		mPauseImageView = (ImageView) findViewById(R.id.recorder_pause);

		mStopImageView.setOnClickListener(this);
		mGoonImageView.setOnClickListener(this);
		mPauseImageView.setOnClickListener(this);

		mTimerFormat = getResources().getString(R.string.timer_format);
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

		//注册广播，监听录音动作
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(INTENT_RECORD_START);
		intentFilter.addAction(INTENT_RECORD_STOP);
		registerReceiver(mRecordBroadcastReceiver,intentFilter);
	}

	private BroadcastReceiver mRecordBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (INTENT_RECORD_START.equals(action)){
				//TODO 开启录音
				mSoundBean = (SoundBean) intent.getSerializableExtra(KEY_RECORD_SOUND);
				if (mSoundBean != null){

					Toast.makeText(HomeActivity.this,"开始录音中...",Toast.LENGTH_SHORT).show();
					startRecorder(mSoundBean.modelName);
				}
			}else if (INTENT_RECORD_STOP.equals(action)){
				//TODO 关闭。保存录音
				stopRecorder();
			}
		}
	};

	private ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i(TAG, "<onServiceConnected> Service connected");
			mService = ((SoundRecorderService.SoundRecorderBinder) service).getService();
			mRecorder = mService.getRecorder();
			mRecorder.setOnStateChangedListener(HomeActivity.this);
			mRemainingTimeCalculator = mService.getRemainingTimeCalculator();
			updateRecorderState();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.i(TAG, "<onServiceDisconnected> Service dis connected");
			mService = null;
		}
	};

	private void updateRecorderState(){
		switch (mService.getRecordState()) {
			case SoundRecorder.STATE_IDLE:// 未录制
				//TODO 此状态，需要隐藏当前的控件
				mMainRelativeLayout.setVisibility(View.GONE);
				mEmptyTextView.setVisibility(View.VISIBLE);
				break;
			case SoundRecorder.STATE_RECORDING:// 录制

				mMainRelativeLayout.setVisibility(View.VISIBLE);
				mEmptyTextView.setVisibility(View.GONE);
				createFileName();
//				SponsorInfo sb = mService.getSponsorInfo();
//				if (mSponsorInfo != null
//						&& mSponsorInfo.getSponsorId().equals(sb.getSponsorId())) {
//					mSoundRecord.setText(R.string.stop_record);//暂停的显示
//					createFileName();
//				} else {
////                    mSoundRecord.setEnabled(false);//录音的按钮，隐藏
//					return;
//				}

				break;
			case SoundRecorder.STATE_STOP_RECORDING:// 停止录制
				mMainRelativeLayout.setVisibility(View.VISIBLE);
				mEmptyTextView.setVisibility(View.GONE);
//                mSoundRecord.setText(R.string.sound_record);
				break;
		}
		updateTimerView();
	}

	//更新时间
	private void updateTimerView() {
		int state = mService.getRecordState();

		boolean ongoing = state == SoundRecorder.STATE_RECORDING
				|| state == SoundRecorder.STATE_PLAYING;

		long time = ongoing ? mService.getCurrentRecordProgress() : mService
				.getRecordSampleLength();

		if (ongoing && time < MAX_RECORD_TIME) {
			String timeStr = String.format(mTimerFormat, time / 60 / 60,
					time / 60, time % 60);
			mTimeTextView.setText(timeStr);
			if (state == SoundRecorder.STATE_PLAYING) {
				// mStateProgressBar.setProgress((int)(100*time/mRecorder.sampleLength()));
			} else if (state == SoundRecorder.STATE_RECORDING) {
				updateTimeRemaining();
			}

			if (ongoing)
				new Handler().postDelayed(mUpdateTimer, 1000);
		}else{
			mService.stopRecording();
		}

	}

	Runnable mUpdateTimer = new Runnable() {
		public void run() {
			updateTimerView();
		}
	};

	private Handler mTimeHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

		}

	};

	private void updateTimeRemaining() {
		long t = mRemainingTimeCalculator.timeRemaining();
		Log.i(TAG,"timeRemaining:" + t);

		if (t <= 0) {

			int limit = mRemainingTimeCalculator.currentLowerLimit();
			switch (limit) {
				case RemainingTimeCalculator.DISK_SPACE_LIMIT:
					mErrorUiMessage = getResources().getString(
							R.string.storage_is_full);
					break;
				case RemainingTimeCalculator.FILE_SIZE_LIMIT:
					mErrorUiMessage = getResources().getString(
							R.string.max_length_reached);
					Toast.makeText(HomeActivity.this, mErrorUiMessage,
							Toast.LENGTH_SHORT).show();
					break;
				default:
					mErrorUiMessage = null;
					break;
			}
			mService.stopRecording();
			return;
		}

	}

	private void createFileName() {
		String fileName = mRecorder.sampleFile().getName();
		mLastFileName = fileName.substring(0, fileName.lastIndexOf(".tmp"));
		mService.setFileName(mLastFileName);
		mFileNameTextView.setText(mLastFileName);
		EventBus.getDefault().post("recorder_start");
	}

	@Override
	public void onStateChanged(int state) {
		if (state == SoundRecorder.STATE_STOP_RECORDING) {
			updateRecorderState();
			showSaveRecordDialog();
		}
	}

	@Override
	public void onError(int error) {

	}

	@Override
	public void onPositive() {
		if (saveSample()) {
			updateRecorderState();
		}
	}

	@Override
	public void onNegative() {
		mLastFileName = null;
		updateRecorderState();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		final int state = mService.getRecordState();
		if (id == R.id.recorder_stop) {
			if (state == SoundRecorder.STATE_RECORDING) {
				stopRecorder();
			}
		} else if (id == R.id.recorder_goon) {
			if (mRecorder.getState() == SoundRecorder.STATE_PAUSE_RECORDING){
				goonRecorder();
			}
		}
	}

	//停止录音（保存文件）
	private void stopRecorder(){
		mService.stopRecording();
	}

	//继续录音
	private void goonRecorder(){
		mRecorder.resumeRecording();
	}

	public void startRecorder(String modelName){
		mRemainingTimeCalculator.reset();
		mService.stopAudioPlayback();
		mService.setSoundBean(mSoundBean);
		mService.setStopRecordCallback(this);

		if ((mAudioManager.getMode() == AudioManager.MODE_IN_CALL)
				&& (mAudioSourceType == MediaRecorder.AudioSource.MIC)) {
			mAudioSourceType = MediaRecorder.AudioSource.VOICE_UPLINK;
			mService.setAudioSourceType(mAudioSourceType);
			Log.e(TAG, "Selected Voice Tx only Source: sourcetype"
					+ mAudioSourceType);
		}

		if (mMaxFileSize != -1 && mMaxFileSize < 1024 * 100) {
			Toast.makeText(this, R.string.max_length_reached,
					Toast.LENGTH_SHORT).show();
			return;
		}
		mService.record(mRequestedType,modelName);

		if (mMaxFileSize != -1) {
			mRemainingTimeCalculator.setFileSizeLimit(
					mService.getRecordSampleFile(), mMaxFileSize);
		}
		updateRecorderState();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i(TAG, "<onResume> start service");
		if (startService(new Intent(this, SoundRecorderService.class)) == null) {
			Log.e(TAG, "<onResume> fail to start service");
			finish();
			return;
		}
		bindService(new Intent(this, SoundRecorderService.class),
				this.mServiceConnection, BIND_AUTO_CREATE);
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mService != null){
			RECORDER_STATE = mService.getRecordState();
		}
	}

	public void showSaveRecordDialog() {
		if (mLastFileName == null) {
			String path = mService.getRecordSampleFile().getName();
			String fileName = path.substring(
					1 + path.lastIndexOf(File.separator), path.length());
			if (fileName.endsWith(".tmp"))
				fileName = fileName.substring(0, fileName.lastIndexOf(".tmp"));
			mLastFileName = fileName;
		}
		if (saveSample()) {
			updateRecorderState();
		}
	}

	private boolean saveSample() {
		if (mService.saveRecord(mLastFileName, mRequestedType)) {
			// 保存音频资源到数据库
			if (mSoundBean != null){
				ImageOrAudioBean bean = new ImageOrAudioBean();
				if (mSoundBean.getServiceId() == UploadToTempSyncLogic.SERVICE.SERVICE_COMMUNITY_SINGLE ||
						mSoundBean.getServiceId() == UploadToTempSyncLogic.SERVICE.SERVICE_COMMUNITY_IMPLODE){
					//TODO 个别教育，活动
					SponsorInfo mSponsorInfo = (SponsorInfo) mSoundBean.getSource();
					bean.setSponsorType(mSoundBean.registerType);
					if (mSponsorInfo != null) {
						bean.setSponsorId(mSponsorInfo.getSponsorId());
					}
				} else if(mSoundBean.getServiceId() == UploadToTempSyncLogic.SERVICE.SERVICE_COMMUNITY_IMPLODE){
					//TODO 集中教育，活动
					SponsorInfo mSponsorInfo = (SponsorInfo) mSoundBean.getSource();
					bean.setSponsorType(mSoundBean.registerType);
					if (mSponsorInfo != null) {
						bean.setSponsorId(mSponsorInfo.getSponsorId());
					}
				} else if(mSoundBean.getServiceId() == UploadToTempSyncLogic.SERVICE.SERVICE_WORK_VISIT){
					//TODO 工作走访
					WorkVisitBean workVisitBean = (WorkVisitBean) mSoundBean.getSource();
					bean.setParentId(String.valueOf(workVisitBean.getId()));
				}
				bean.setServiceId(mSoundBean.getServiceId());
				bean.setFileName(mLastFileName);
				bean.setFileType(2);
				String path = mRecorder.getSampleDir().getAbsolutePath() + "/"
						+ mLastFileName + mRecorder.getType();
				bean.setFilePath(path);
				bean.setState(1);
				bean.setImie(AppContext.getInstance().getImei());
				mKjdb.save(bean);

				updateRecorderState();
				//TODO 发送录音完成的广播
				EventBus.getDefault().post("recorder_finished");
			}
			return true;
		} else {
			mLastFileName = null;
			return false;
		}
	}

}
